package com.kcwl.idea.plugins.base;

import com.kcwl.idea.plugins.base.utils.StrUtil;
import com.intellij.psi.*;

public class AnnotationUtil {
    public static PsiAnnotation findAnnotation(PsiField field, String annotationName) {
        PsiAnnotation[] annotations = field.getAnnotations();
        for (PsiAnnotation annotation : annotations) {
            if (annotation.getQualifiedName().equals(annotationName)) {
                return annotation;
            }
        }
        return null;
    }

    public static PsiAnnotation findAnnotation(PsiClass psiClass, String annotationName) {
        PsiAnnotation[] annotations = psiClass.getAnnotations();
        for (PsiAnnotation annotation : annotations) {
            if (annotation.getQualifiedName().equals(annotationName)) {
                return annotation;
            }
        }
        return null;
    }

    public static void removeAnnotation(PsiField field, String annotationName) {
        PsiAnnotation[] annotations = field.getAnnotations();
        for (PsiAnnotation annotation : annotations) {
            if (annotation.getQualifiedName().equals(annotationName)) {
                annotation.delete();
            }
        }
    }

    public static void removeAnnotation(PsiClass psiClass, String annotationName) {
        PsiAnnotation[] annotations = psiClass.getAnnotations();
        for (PsiAnnotation annotation : annotations) {
            if (annotation.getQualifiedName().equals(annotationName)) {
                annotation.delete();
            }
        }
    }

    /**
     * 获取注解上的value
     * @param annotation
     * @return
     */
    public static String processAnnotation(PsiAnnotation annotation) {
        if (annotation == null) {
            return "";
        }
        // 处理注解的逻辑
        PsiAnnotationMemberValue psiAnnotationMemberValue = annotation.findAttributeValue("value");
        if (psiAnnotationMemberValue == null) {
            return "";
        }
        return StrUtil.removeAll(psiAnnotationMemberValue.getText(), "\"") ;
    }
}
